package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    //制造转化器的方法
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        //返回具体转化器
        return  new Converter<String,T>(){
            //定义转化方法
            @Override
            public T convert(String source){
                //1.获取枚举的全部值
                //ItemType.values();//枚举的.values获取全部值
                //2.循环获取枚举的getCode和source对象
                for (T enumConstant:targetType.getEnumConstants()){
                    //3.如何相同直接返回类型
                    if(enumConstant.getCode()==Integer.parseInt(source)){
                        return  enumConstant;
                    }
                }
                //4.循环以后没有抛出异常
                throw new RuntimeException("没有找到对应的枚举类型");
            }
        };
    }
}
